package com.syncshot.androidapp.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.syncshot.androidapp.Constant;
import com.syncshot.androidapp.R;
import com.syncshot.androidapp.helper.NotificationHelper;
import com.syncshot.androidapp.helper.NotificationHelper.RegistrationListener;
import com.syncshot.androidapp.helper.WSHelper.Call;
import com.syncshot.androidapp.helper.WSHelper.WebserviceCaller;
import com.syncshot.androidapp.helper.WSHelper.WebserviceCaller.WebserviceCallerListener;
import com.syncshot.androidapp.model.Event;
import com.syncshot.androidapp.model.Me;
import com.syncshot.androidapp.model.ServerTime;
import com.syncshot.androidapp.model.User;
import com.syncshot.androidapp.util.WSUtil;

public class HomeActivity extends AbstractActivity implements WebserviceCallerListener, RegistrationListener {

    private static final String TAG                    = "HomeActivity";

    private View                mShootButton;
    private BroadcastReceiver   mRegistrationBroadcastreceiver;
    private BroadcastReceiver   mUSerBroadcastReceiver = new BroadcastReceiver() {
                                                           @Override
                                                           public void onReceive(Context context, Intent intent) {
                                                               updateUsersList();
                                                           }
                                                       };

    private Event               mEvent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        NotificationHelper.getInstance().setApplicationContext(getApplicationContext());
        
        if(NotificationHelper.getInstance().isFullyRegistered()){
        	Me me = new Me();
            me.setLatitude(10);
            me.setLongitude(10);
            SharedPreferences settings = getSharedPreferences(Constant.PREF, 0);
            me.setUser(settings.getString(Constant.PREF_USERNAME, null));

            String key = settings.getString(Constant.PREF_PUSHD, "");
            me.setPushDid(key);
            (new WebserviceCaller(this)).execute(WSUtil.generateCallUpdateUserLocation(me));
        }

        

        try {
            GCMRegistrar.checkDevice(this);
            GCMRegistrar.checkManifest(this);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), getString(R.string.unsupportedDevice), Toast.LENGTH_LONG).show();
        }

        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            GCMRegistrar.register(this, Constant.GCM_SENDER_ID);
        } else {
            // We are already registered to google. But what about pushd ? let's check it
            Log.v(TAG, "Already registered" + GCMRegistrar.getRegistrationId(this));
            if (getSharedPreferences(Constant.PREF, 0).getString(Constant.PREF_PUSHD, "") == "") {// We need to call pushd
                NotificationHelper.getInstance().setApplicationContext(getApplicationContext());
                NotificationHelper.getInstance().startRegistrationProcess(this);
            }
        }

        mRegistrationBroadcastreceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        handleReadiness();
                    }
                });
            }
        };

        registerReceiver(mRegistrationBroadcastreceiver, new IntentFilter(Constant.REGISTERED_BROADCAST));

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshDisplayEvent();

        registerReceiver(mUSerBroadcastReceiver, new IntentFilter(Constant.BROADCAST_NEW_USER));

        registerReceiver(mRegistrationBroadcastreceiver, new IntentFilter(Constant.REGISTERED_BROADCAST));
        handleReadiness();

        WebserviceCaller ws = new WebserviceCaller(this);
        ws.execute(WSUtil.generateCallEventList("10", "10"));
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mRegistrationBroadcastreceiver != null) {
            unregisterReceiver(mRegistrationBroadcastreceiver);
        }
        if (mUSerBroadcastReceiver != null) {
            unregisterReceiver(mUSerBroadcastReceiver);
        }

    }

    private void handleReadiness() {

    }

    public void onClickCreateEvent(View view) {
        startActivity(new Intent(this, CreateEventActivity.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_home, menu);
        return true;
    }

    public void onClickPhoto(View view) {
        startActivity(new Intent(this, TakePictureActivity.class));
    }

    public void onClickJoinEvent(View view) {
        if (mEvent != null) {

            Intent intent = new Intent(this, WaitingRoomActivity.class);
            intent.putExtra(Constant.KEY_EVENT_ID, String.valueOf(mEvent.getId()));
            startActivity(intent);
            mEvent = null;
        }
    }

    private void refreshDisplayEvent() {
//        if (mEvent != null) {
//
//            ((TextView) findViewById(R.id.project_event_textview)).setText(mEvent.getDescription());
//            findViewById(R.id.create_event_layout).setVisibility(View.GONE);
//            findViewById(R.id.join_event_layout).setVisibility(View.VISIBLE);
//
//            updateUsersList();
//        } else {
//            findViewById(R.id.create_event_layout).setVisibility(View.VISIBLE);
//            findViewById(R.id.join_event_layout).setVisibility(View.GONE);
//        }
    }

    private void updateUsersList() {
        if (mEvent != null) {
            WebserviceCaller ws = new WebserviceCaller(this);
            ws.execute(WSUtil.generateCallUserList(String.valueOf(mEvent.getId())));
        }
    }

    @Override
    public void onResult(Call call, Object result) {
        Log.v("", "onResult : " + result);

        if (result instanceof ServerTime) {
            ServerTime st = ((ServerTime) result);
            int diff = (int) (System.currentTimeMillis() - st.getServerTime());

            SharedPreferences settings = getSharedPreferences(Constant.PREF, 0);
            int diffSaved = settings.getInt(Constant.PREF_DIFF_SERVERTIME, Integer.MAX_VALUE);
            if (Math.abs(diff) < Math.abs(diffSaved)) {
                settings.edit().putInt(Constant.PREF_DIFF_SERVERTIME, (int) diff).apply();
            }
        } else if (result instanceof Event[]) {
            Event[] listEvent = (Event[]) result;
            if (listEvent != null && listEvent.length >= 1) {
                mEvent = listEvent[0];
                refreshDisplayEvent();
            }
        } else if (result instanceof User[]) {
            ((TextView) findViewById(R.id.number_user_textview)).setText("+" + ((User[]) result).length);
        }
    }

    @Override
    public void onRegistrationCompleted() {
        handleReadiness();
    }

}
